package com.lss.myapp.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import androidx.activity.EdgeToEdge;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.gson.Gson;
import com.lss.myapp.R;
import com.lss.myapp.constant.AppConfig;
import com.lss.myapp.entity.LoginResp;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends BaseActivity implements View.OnClickListener {


    private EditText etAccount;
    private EditText etPwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_login);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        etAccount = findViewById(R.id.et_login_accout);
        etPwd = findViewById(R.id.et_login_pwd);
        findViewById(R.id.btn_login).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.btn_login) {
            String account = etAccount.getText().toString().trim();
            String pwd = etPwd.getText().toString().trim();
            if (account.isEmpty()) {
                showToast("请输入账户");
                return;
            }
            if (pwd.isEmpty()) {
                showToast("请输入密码");
                return;
            }
            // okhttp3 account pwd post请求
            // 使用 OkHttp3 发送 POST 请求
            OkHttpClient client = new OkHttpClient();
            MediaType JSON = MediaType.get("application/json; charset=utf-8");
            JSONObject jsonBody = new JSONObject();
            try {
                jsonBody.put("mobile", account);
                jsonBody.put("password", pwd);  // 实际使用中建议加密后再传输
            } catch (JSONException e) {
                e.printStackTrace();
            }
            RequestBody requestBody = RequestBody.create(jsonBody.toString(), JSON);

            // 构建请求
            Request request = new Request.Builder()
                    .url(AppConfig.BASE_URL + "/app/login")  // 替换为你的登录接口地址
                    .post(requestBody)
                    .build();

            // 异步请求
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(() -> showToast("网络请求失败: " + e.getMessage()));
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String responseData = response.body().string();
                    if (response.isSuccessful()) {
                        Log.i("lss-test", responseData);
                        Gson gson = new Gson();
                        LoginResp loginResp = gson.fromJson(responseData, LoginResp.class);
                        Log.i("lss-test", loginResp.toString());
                        if (loginResp != null && loginResp.getCode() == 0) {
                            Log.i("lss-test", loginResp.toString());
                            saveUserToken(loginResp.getToken(), loginResp.getExpire());
                            navigateTo(HomeActivity.class);
                            showToastSync("登录成功");
                        } else {
                            showToastSync("登录失败，请重试");
                        }
                        // 解决ui线程阻塞的问题
                        runOnUiThread(() -> {
                            navigateTo(HomeActivity.class);
                            showToast("登录成功");
                            // TODO: 处理登录成功后的跳转或其他逻辑
                        });
                    } else {
                        runOnUiThread(() -> showToast("登录失败，请检查账户或密码" + response));
                        Log.i("lss-test", String.valueOf(response));
                    }
                }
            });
//            // 构建请求参数
//            Map<String, String> params = new HashMap<>();
//            params.put("mobile", account);
//            params.put("password", pwd);
//
//// 执行异步请求
//            HttpUtil.postAsync(AppConfig.BASE_URL + "/app/login", params,
//                    // 成功回调
//                    response -> {
//                        try {
//                            JSONObject json = new JSONObject(response);
//                            if (json.getInt("code") == 200) {
//                                showToast("登录成功");
////                                startActivity(new Intent(this, MainActivity.class));
//
//                            } else {
//                                showToast(json.getString("message"));
//                            }
//                        } catch (JSONException e) {
//                            showToast("数据解析失败");
//                        }
//                    },
//                    // 失败回调
//                    e -> {
//                        String errorMsg = e.getMessage() != null ? e.getMessage() : "未知错误";
//                        showToast("请求失败: " + errorMsg);
//                    });
        }
    }
}